package com.atguigu.gulimall.cart.controller;

import com.atguigu.common.utils.R;
import com.atguigu.gulimall.cart.service.CartService;
import com.atguigu.gulimall.cart.vo.Cart;
import com.atguigu.gulimall.cart.vo.CartItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/cart")
public class CartController {


    @Autowired
    CartService cartService;

    @GetMapping("/cartItems")
    public List<CartItem> getCurrentUserCartItems(){
        return cartService.getUserCartItems();
    }

    /**
     * 购物车勾选某个商品
     * @param skuId
     * @param check
     * @return
     */
    @RequestMapping("/check")
    public R checkItem(@RequestParam("skuId") Long skuId,
                       @RequestParam("check") Integer check){
        cartService.checkItem(skuId,check);
        return R.ok();
    }

    @RequestMapping("/delete")
    public R deleteCartItem(@RequestParam("skuId") Long skuId){
        int count = cartService.deleteCartItem(skuId);
        if(count > 0){
            return R.ok();
        }
        return R.error();
    }


    /**
     * 更改购物车中某项商品的数量
     * @return
     */
    @GetMapping("/countChange")
    public R changeCartItemNum(@RequestParam("skuId") Long skuId,@RequestParam("num") Integer num){
        CartItem cartItem = cartService.countChange(skuId,num);
        return R.ok();
    }

    @GetMapping("/cartItem/{skuId}")
    public R cartItem(@PathVariable("skuId") Long skuId){
        CartItem item = cartService.getCartItem(skuId);
        if(item == null){
            return R.error();
        }
        return R.ok().put("data",item);
    }

    @GetMapping("/cart")
    public R cartList(){
//        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        Cart cart = cartService.listCart();

        return null;
    }

    @GetMapping("/addToCart")
    public R addToCart(@RequestParam("skuId") Long skuId,@RequestParam("num") Integer num){
//       TODO 不停刷新会不停的添加，接口幂等性问题 ！！！
        CartItem cartItem = cartService.addToCart(skuId,num);
        return R.ok().put("data",cartItem);
    }
}
